package com.boot.realm;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

@Slf4j
@Component
public class UserRealm extends AuthorizingRealm {
    /**
     * 授权:这里是登录后的用户 拥有哪些权限
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String userName = (String) principals.getPrimaryPrincipal();
        log.info("userName--->{}",userName);

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //默认给个admin角色
        Set<String> roles = new HashSet<>();
        roles.add("admin");
        authorizationInfo.setRoles(roles);
        Set<String> perms = new HashSet<>();
        //默认给user、menu权限
        perms.add("user:*");
        perms.add("menu:*");
        authorizationInfo.setStringPermissions(perms);

        return authorizationInfo;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = (String) token.getPrincipal();

        String password = "123456";//从数据库查询到的密码

        //将/login中登录的userName拿到 从数据库中查询到密码 放到shiro中
        //shiro会去比对/login输入的密码和数据库查询到的密码是否匹配
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userName,password,getName());

        return authenticationInfo;
    }
}
